#include"UdpServe.hpp"
#include "ThreadPool.hpp"
#include<vector>
using task_t = std::function<void()>;
class route{
public:
    route(){
        pthread_mutex_init(&_mutex, nullptr);
    }
    ~route(){

    }
    bool IsOline(InetAddr who){
        LockGuard lockguard(&_mutex);
        if(online.empty()){
        online.push_back(who);
        std::cout<<"表空插入成功"<<std::endl;
            return false;
        }
        else{
            for(auto &e:online){
               std::cout <<"ip"<<e.Ip()<<"port"<<e.Port()<<std::endl;
                std::cout <<"ip"<<who.Ip()<<"port"<<who.Port()<<std::endl;
                if(e==who)
                return true;
            }
        online.push_back(who);
        std::cout<<"插入成功"<<std::endl;
            return false;
        }
    }
    void act(int socked,InetAddr who,std::string mes){
    LockGuard lockguard(&_mutex);
    for(auto &e:online){
    struct sockaddr_in local(e.addr());
    socklen_t len=sizeof(local);
    sendto(socked,mes.c_str(),mes.size(),0,(sockaddr*)&local,len);
    std::cout<<"server 发送成功"<<"ip"<<who.Ip()<<"port"<<who.Port()<<std::endl;
    }
    }
    void foward(int socked,InetAddr who,std::string mes){
        IsOline(who);
        task_t task=std::bind(&route::act,this,socked,who,mes);
        ThreadPool<task_t>::GetInstance()->Equeue(task);
    }
private:
    std::vector<InetAddr> online;
    pthread_mutex_t _mutex;
};